﻿Imports System.Net
Imports System.Text
Imports LSW.Extension

Namespace Api
    Public Class AdmAuthentication
        Public Shared ReadOnly DatamarketAccessUri As String = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13"
        Private clientId As String
        Private clientSecret As String
        Private request As String

        Public Sub New(clientId As String, clientSecret As String)
            Me.clientId = clientId
            Me.clientSecret = clientSecret
            'If clientid or client secret has special characters, encode before sending request
            Me.request = String.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", WebUtility.UrlEncode(clientId), WebUtility.UrlEncode(clientSecret))
        End Sub

        Public Function GetAccessToken() As Task(Of AdmAccessToken)
            Return HttpPost(DatamarketAccessUri, request)
        End Function

        Private Async Function HttpPost(DatamarketAccessUri As String, requestDetails As String) As Task(Of AdmAccessToken)
            'Prepare OAuth request 
            Dim webRequest As WebRequest = WebRequest.Create(DatamarketAccessUri)
            webRequest.ContentType = "application/x-www-form-urlencoded"
            webRequest.Method = "POST"
            Dim bytes As Byte() = Encoding.UTF8.GetBytes(requestDetails)
            Using outputStream As Stream = Await webRequest.GetRequestStreamAsync
                outputStream.Write(bytes, 0, bytes.Length)
            End Using
            Using webResponse As WebResponse = Await webRequest.GetResponseAsync
                'Get deserialized object from JSON stream
                Dim token As AdmAccessToken = webResponse.GetResponseStream.JSONToObj(Of AdmAccessToken)()
                Return token
            End Using
        End Function
    End Class
End Namespace